<template>
  <div class="app-container customer-div">
    <el-menu :default-active="tab" class="el-menu-demo" mode="horizontal" @select="handleSelect">
      <el-menu-item index="isMy">我的</el-menu-item>
      <el-menu-item index="all">全部</el-menu-item>
      <el-menu-item index="1">复核待处理</el-menu-item>
    </el-menu>
    <div style="margin-top: 40px">
      <!--搜索-->
      <el-form :inline="true" :model="listQuery" size="mini" label-width="100px">
        <el-form-item label="发货单号：">
          <el-input v-model="listQuery.deliverSn"></el-input>
        </el-form-item>
        <!--        <el-form-item label="订单时间：">-->
        <!--          <el-date-picker-->
        <!--                  :default-time="['00:00:00', '23:59:59']"-->
        <!--                  v-model="listQuery.createDate"-->
        <!--                  type="daterange"-->
        <!--                  format="yyyy 年 MM 月 dd 日"-->
        <!--                  value-format="yyyy-MM-dd HH:mm:ss"-->
        <!--                  range-separator="至"-->
        <!--                  start-placeholder="开始日期"-->
        <!--                  end-placeholder="结束日期">-->
        <!--          </el-date-picker>-->
        <!--        </el-form-item>-->
        <el-form-item label="发货日期：">
          <el-date-picker :default-time="['00:00:00', '23:59:59']" v-model="listQuery.deliverDate" type="daterange"
            format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="客户编号：">
          <el-input v-model="listQuery.customerNumber"></el-input>
          <!--          <el-autocomplete-->
          <!--                  clearable-->
          <!--                  class="inline-input"-->
          <!--                  value-key="customerName"-->
          <!--                  :fetch-suggestions="querySearch"-->
          <!--                  v-model="listQuery.customerName"-->
          <!--                  placeholder="请输入内容"-->
          <!--                  @select="handleSelectCustomerName"-->
          <!--                  :trigger-on-focus="false"-->
          <!--                  style="width: 260px;"-->
          <!--          ></el-autocomplete>-->
        </el-form-item>
        <el-form-item label="业务员：">
          <el-select v-model="listQuery.userId" filterable placeholder="请选择" clearable>
            <el-option v-for="item in userOptionList" :key="item.userId" :label="item.userName" :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="品名：">
          <el-input v-model="listQuery.goodsName"></el-input>
        </el-form-item>
        <el-form-item label="送货类型：">
          <el-select v-model="listQuery.isYunlianDeliver" filterable placeholder="请选择" clearable>
            <el-option :key="1" label="运联发货" :value="1">
            </el-option>
            <el-option :key="0" label="采购发货" :value="0">
            </el-option>
            <el-option :key="2" label="自提" :value="2">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单号：">
          <el-input v-model="listQuery.orderSn"></el-input>
        </el-form-item>
        <el-form-item label="采购评级：">
          <el-select v-model.number="listQuery.customerLabel" class="input-width" style="width:195px" placeholder="请选择"
            clearable>
            <el-option value="A类" label="A类" key="A类"></el-option>
            <el-option value="B类" label="B类" key="B类"></el-option>
            <el-option value="C类" label="C类" key="C类"></el-option>
            <el-option value="D类" label="D类" key="D类"></el-option>
            <el-option value="E类" label="E类" key="E类"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="牌号：">
          <el-select v-model="listQuery.kingGoodsId" filterable placeholder="请选择" clearable>
            <el-option v-for="item in goodsList" :key="item.kingId" :label="item.goodsSn" :value="item.kingId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采购源单号：">
          <el-input v-model="listQuery.purchaseEntrySn"></el-input>
        </el-form-item>
        <el-form-item label="供应商：">
          <el-select clearable v-model="listQuery.supplierId" filterable reserve-keyword placeholder="请输入关键词">
            <el-option v-for="item in options2" :key="item.supplierId" :label="item.supplierName"
              :value="item.supplierId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采购员：">
          <el-select v-model="listQuery.purchaseUserId" filterable placeholder="请选择" clearable>
            <el-option v-for="item in userOptionList" :key="item.userId" :label="item.userName" :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="订单类型：">
          <el-select v-model="listQuery.isMoresuOnlineOrder" class="input-width" style="width:150px" placeholder="请选择"
            clearable>
            <el-option :key="0" label="销售订单" :value="0"></el-option>
            <el-option :key="1" label="推广订单" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否过滤订单：">
          <el-select style="width:100px" v-model="listQuery.isFilterOrder" clearable>
            <el-option label="否" :value="0"></el-option>
            <el-option label="是" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否长协：">
          <el-select v-model="listQuery.isAgreement" placeholder="请选择" clearable>
            <el-option label="是" :value="1"></el-option>
            <el-option label="否" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleSearchList()" type="primary">
            查询
          </el-button>
          <el-button v-if="purchaseDeliverDetailsExport" :loading="btnLoading2" @click="downloadExcel()">
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!--数据列表-->
    <div style="font-size:14px;line-height: 30px;padding:10px 0 ">
      发货数量：<span style="font-weight: bold;padding-right:10px">{{ sendAllNum }}</span>采购毛利：<span
        style="font-weight: bold;padding-right:10px">{{ purchaseProfit }}</span>
    </div>
    <div class="table-container">
      <el-table v-loading="listLoading" :data="tableData" border style="width: 100%; margin-top: 20px">
        <el-table-column label="订单号" width="150" align="center">
          <template slot-scope="scope">
            <el-link type="primary" @click="toDetail('see', scope.row)" style="font-size:12px;vertical-align: middle">
              {{ scope.row.orderSn }}
            </el-link>
            <img src="../../assets/images/xianshang.png" v-if="scope.row.isMoresuOnlineOrder == 1"
              style="vertical-align: middle;" />
          </template>
        </el-table-column>
        <el-table-column label="送货类型" align="center" width="100">
          <template slot-scope="scope">
            {{ scope.row.sendType }}
          </template>
        </el-table-column>
        <el-table-column label="业务员" width="100" align="center">
          <template slot-scope="scope">
            {{ scope.row.userRealName }}
          </template>
        </el-table-column>
        <el-table-column label="客户编号" width="300">
          <template slot-scope="scope">
            <div>{{ scope.row.customerNumber }}</div>
            <!--是否有权限-->
            <div v-if="scope.row.isShowCustomerName">{{ scope.row.customerName }}</div>
          </template>
        </el-table-column>
        <el-table-column label="供应商" width="300">
          <template slot-scope="scope">
            {{ scope.row.supplierName }}
          </template>
        </el-table-column>
        <el-table-column label="牌号" align="center" width="150">
          <template slot-scope="scope">
            {{ scope.row.goodsSn }}
          </template>
        </el-table-column>
        <el-table-column label="订单单价" width="100" align="center">
          <template slot-scope="scope">
            {{ scope.row.goodsPrice }}
          </template>
        </el-table-column>

        <el-table-column label="本次发货数量" width="120" align="center">
          <template slot-scope="scope">
            {{ scope.row.shipNum }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="销售合同结算方式" width="150">
          <template slot-scope="scope">
            {{ scope.row.salePayMethod }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="成本价结算方式" width="150">
          <template slot-scope="scope">
            {{ scope.row.goodsPayMethod }}
          </template>
        </el-table-column>

        <el-table-column label="实际含税运费" width="120" align="center">
          <template slot-scope="scope">
            {{ scope.row.actualTaxFreight }}
          </template>
        </el-table-column>
        <el-table-column :render-header="renderHeader2" width="100" align="center">
          <template slot-scope="scope">
            {{ scope.row.costCashPrice }}
          </template>
        </el-table-column>
        <el-table-column label="采购底价" width="100" align="center">
          <template slot-scope="scope">
            {{ scope.row.purchaseActualPrice }}
          </template>
        </el-table-column>
        <el-table-column label="销售发货现金价毛利" width="140" align="center">
          <template slot-scope="scope">
            {{ scope.row.saleProfit }}
          </template>
        </el-table-column>
        <el-table-column label="采购延迟金" width="140" align="center" prop="purchaseInterest">
        </el-table-column>
        <el-table-column label="采购现金价毛利" width="120" align="center">
          <template slot-scope="scope">
            <span style="color:red" v-if="scope.row.purchaseProfit < 0">{{ scope.row.purchaseProfit }}</span>
            <span v-else>{{ scope.row.purchaseProfit }}</span>
          </template>
        </el-table-column>
        <el-table-column label="总毛利" width="120" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.purchaseProfit | fifsum(scope.row.saleProfit) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订单行备注" width="400">
          <template slot-scope="scope">
            {{ scope.row.remark }}
          </template>
        </el-table-column>

        <el-table-column width="100" fixed="right" label="操作" align="center">
          <template slot-scope="scope">
            <el-button v-if="scope.row.isNeedRecheck == 1" type="text" size="mini" @click="toDetail('see', scope.row)">复核
            </el-button>

          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper" :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize" :page-sizes="[10, 15, 20]" :total="count">
      </el-pagination>
    </div>

  </div>
</template>
<script>
import { getCustomerOption, supplierList, getOrderUsersList, getDeliverDetailList, exportDeliverDetailList, orderGoodsList } from '@/api/partner'
import { formatDate } from '@/utils/date';
import store from '@/store'
import { mapGetters } from 'vuex'
const defaultListQuery = {
  pageNum: 1,
  pageSize: 10,
  goodsName: '',
  createDate: null,
  deliverDate: null,
  customerName: null,
  deliverSn: '',
  userId: '',
  type: 'isMy',
  isYunlianDeliver: '',
  orderSn: '',
  customerLabel: '',
  goodsSn: '',
  supplierId: '',
  purchaseEntrySn: '',
  kingGoodsId: '',
  purchaseUserId: '',
  isMoresuOnlineOrder: '',
  isNeedRecheck: 'all',
  isFilterOrder: '',
  isAgreement: '',
  customerNumber: ''
};
export default {
  name: "index",
  data() {
    return {
      listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
      tableData: [],
      count: 0,
      listLoading: false,
      roles: store.getters.roles ? store.getters.roles : [],
      userOptionList: [],
      saleProfit: '',
      sendAllNum: '',
      purchaseProfit: '',
      btnLoading2: false,
      options2: [],
      goodsList: [],
      tab: 'isMy'
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),

    isCanSaleByDept() {
      if (this.roles.indexOf("saleDept") != -1) {
        return true
      } else {
        return false
      }
    },
    isCanSaleByAll() {
      if (this.roles.indexOf("saleAll") != -1) {
        return true
      } else {
        return false
      }
    },
    purchaseDeliverDetailsExport() {
      if (this.roles.indexOf("purchaseDeliverDetailsExport") != -1) {
        return true
      } else {
        return false
      }
    },
  },
  created() {
    this.listQuery.deliverDate = this.getNowMon();
    this.getList();
    this.getUserOptionList();
    this.getSupplierList();
    this.getOrderGoodsList();
  },
  filters: {
    formatCreateTime(time) {
      if (time) {
        let date = new Date(time);
        return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
      } else {
        return '--'
      }
    },
    fifsum(val, val2) {
      let num = val ? parseFloat(val) : 0;
      let num2 = val2 ? parseFloat(val2) : 0;
      return (num + num2).toFixed(2)
    },
  },
  methods: {
    //获取本月第一天与最后一天
    getNowMon() {
      var now = new Date(); //当前日期
      var nowMonth = now.getMonth(); //当前月
      var nowYear = now.getFullYear(); //当前年
      //本月的开始时间
      var monthStartDate = new Date(nowYear, nowMonth, 1);
      //本月的结束时间
      var monthEndDate = new Date(nowYear, nowMonth + 1, 0);
      var timeStar = Date.parse(monthStartDate);//s
      var timeEnd = Date.parse(monthEndDate);//s
      let endDate = formatDate(new Date(timeEnd), 'yyyy-MM-dd');
      let startDate = formatDate(new Date(timeStar), 'yyyy-MM-dd');
      return [startDate, endDate]
    },
    //获取上个月第一天与最后一天
    getLastmon() {
      var nowdays = new Date();
      var year = nowdays.getFullYear();
      var month = nowdays.getMonth();
      if (month == 0) {
        month = 12;
        year = year - 1;
      }
      if (month < 10) {
        month = "0" + month;
      }
      var firstDay = year + "-" + month + "-" + "01";//上个月的第一天
      var myDate = new Date(year, month, 0);
      var lastDay = year + "-" + month + "-" + myDate.getDate();//上个月的最后一天
      console.log([firstDay, lastDay])
      return [firstDay, lastDay]
    },
    //去详情页
    toDetail(type, item) {
      let routeData = this.$router.resolve({ name: 'purchaseDetail', query: { id: item.orderId, type: type } });
      window.open(routeData.href);
      // this.$router.push({name:'purchaseDetail',query:{id:item.orderId,type:type}})
    },
    getOrderGoodsList() {
      orderGoodsList().then((res) => {
        this.goodsList = res.list
      })
    },
    //供应商
    getSupplierList() {
      supplierList().then((res) => {
        this.options2 = res;
      })
    },

    renderHeader(h) {
      return [h('div', {}, ['金蝶']), h('div', {}, ['成本单价'])]
    },

    renderHeader2(h) {
      return [h('div', {}, ['成本单价']), h('div', {}, ['现金价'])]
    },
    renderHeader3(h) {
      return [h('div', {}, ['采购底价']), h('div', {}, ['现金价'])]
    },

    //获取员工下拉选项
    getUserOptionList() {
      getOrderUsersList().then((res) => {
        this.userOptionList = res;
      })
    },

    //选择员工名称
    handleSelectUserName(key, item) {
      this.listQuery[key] = item.userId;
    },


    //客户名称输入匹配
    querySearch(queryString, cb) {
      getCustomerOption({ keywords: queryString }).then((res) => {
        cb(res);
      })
    },


    //选择客户名称
    handleSelectCustomerName(item) {
      this.listQuery.keywords = item.customerName
    },

    /**
     * 切换选择状态
     */
    handleSelect(key, keyPath) {
      if (key == 'isMy') {
        this.listQuery.type = key
        this.listQuery.isNeedRecheck = 'all';
        this.listQuery.deliverDate = this.getNowMon();
      } else {
        this.listQuery.type = 'purchase'
        this.listQuery.isNeedRecheck = key;
        if (key == 'all') {
          this.listQuery.deliverDate = this.getNowMon();
        } else {
          let lastmon = this.getLastmon();
          let nowMon = this.getNowMon()
          this.listQuery.deliverDate = [lastmon[0],nowMon[1]]
        }
      }

      this.handleSearchList();
    },
    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },

    handleSearchList() {
      this.listQuery.pageNum = 1;
      this.getList();
    },

    //获取发货明细列表
    getList() {
      this.listLoading = true;
      getDeliverDetailList(this.listQuery).then(response => {
        this.tableData = response.list;
        this.count = response.count;
        this.listLoading = false;
        this.saleProfit = response.saleProfit;
        this.sendAllNum = response.sendAllNum;
        this.purchaseProfit = response.purchaseProfit;
      }).catch(() => {
        this.listLoading = false;
      });
    },

    //下载excle
    downloadExcel() {
      this.btnLoading2 = true;
      let params = JSON.parse(JSON.stringify(this.listQuery));
      params.type = 'purchase';
      exportDeliverDetailList(params).then((res) => {
        this.btnLoading2 = false;
        require.ensure([], () => {
          const { export_json_to_excel } = require('sheet/Export2Excel');
          const tHeader = res.title;
          const filterVal = res.columns;
          const list = res.list;
          const data = this.formatJson(filterVal, list);
          export_json_to_excel(tHeader, data, res.fileName);
        })
      }).catch(() => {
        this.btnLoading2 = false;
      })
    },

    //下载表格数据格式化
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },

  },
}
</script>

<style scoped lang="scss">
.upload-div {
  text-align: center;
  position: relative;

  #upload {

    opacity: 0;
    position: absolute;
    z-index: 1;
    width: 154px;
    height: 40px
  }
}
</style>
